<template>
	<view class="chatting-container">
		<!-- 自定义导航栏 -->
		<view>
			<u-navbar :is-back="false" title="">
				<view class="custom-navbar">
					<view class="nav-left" @click="customBack">
						<u-icon  name="arrow-left" color="#000000" size="34"></u-icon>
					</view>
					<view class="nav-center u-flex u-row-center u-col-center">
						<view>{{currentChatGroup.chatGroupName}}</view>
						<view v-if="currentChatGroup.memberCounts!=undefined&&currentChatGroup.chatGroupType!=0">{{"("+currentChatGroup.memberCounts+")"}}</view>
						<view v-if="currentChatGroup.memberTipStatus==1">
							<u-icon v-show="currentChatGroup.memberTipStatus==1" name="/static/image/chat/pinbi.png" color="#c0c4cc" size="28"></u-icon>
						</view>
					</view>
					<view class="nav-right"  @click="toGroupDetail">
						<u-icon name="more-dot-fill" color="#000000" size="34"></u-icon>
					</view>
				</view>
			</u-navbar>
		</view>
	<!-- 	<view style="width: 100%;" class="u-flex u-row-center u-col-center"><u-loading :show="loadingmMore" mode="flower" size="38"></u-loading></view> -->
		<view   style="position: fixed;z-index: 1000;width: 100%;"  
				v-if="advShow==true&&currentChatGroup.chatNotice!=null&&currentChatGroup.chatNotice.length>0">
			<u-notice-bar @close="advShow=false" padding="20rpx 24rpx" close-icon speed="180"  type="success" :list="currentChatGroup.chatNotice.split(',')"></u-notice-bar>
		</view>
		<view class="msg-container" v-if="messageList.length>0">
			<scroll-view :scroll-y="true" 
						 class="msg-box-scroller" 
						 :style="'height:'+scrollViewHeight+'px'"
						 :scroll-into-view="scrollIntoView"
						 :scroll-top="scrollTop"
						 :scroll-with-animation="scrollAnimation"
						 @scrolltoupper="loadMoreHistoryMsg"
						 lower-threshold="20"
						 upper-threshold="20"
						 @scroll="scrollViewScrolling"
						@touchstart="hideDrawer">
					<view class="message" v-for="(item, index) in messageList" :key="index">
						<view v-if="item.msgType==2" class="sys-msg-box">
							<view style="text-align: center;color:#909399;font-style: oblique;">{{item.createTime}}</view>
							<view  style="text-align: center;color:#909399;">{{parseContent(item)}}</view>
						</view>
						
						<view  v-if="item.msgType==1"   class="message-item " :class="item.meFlag ? 'right' : 'left'"  style="margin-bottom: 4rpx; color:#909399;font-style: oblique;font-size: 20rpx;">
							<text v-if="currentChatGroup.chatGroupType!=0"  :class="item.meFlag?'u-m-l-10':'u-m-r-10'">{{item.userName}}</text><text>{{item.createTime.substring(0,16)}}</text>
						</view>
						
						<view v-if="item.msgType==1" class="message-item " :class="item.meFlag ? 'right' : 'left'">
							<u-image :src="item.userAvatar" width="80" height="80" border-radius="5">
								<view slot="error">
									<u-icon name="chat-fill" color="#19be6b" size="64"></u-icon>
								</view>
								<u-loading slot="loading"></u-loading>
							</u-image>
							<!-- contentType = 1 文本 -->
							<view class="content" v-if="item.contentType == 1"  @longpress="showToolTip($event,index)">
								<view class="richTextImg">
									<rich-text :nodes="parseContent(item)" :selectable="false" preview="false"></rich-text>
								</view>
							</view>
							<!-- contentType = 3 语音 playAudi  @tap="playVoice(item)"o -->
							<view  	v-if="item.contentType == 4" @tap="handleAudio(item)"
								class="content contentType2" :class="[{ 'content-type-right': item.meFlag }]"
								hover-class="contentType2-hover-class"
								:style="{width:`${130+(JSON.parse(item.content).contentDuration*2)}rpx`}">
								<view class="voice_icon" :class="[
										{ voice_icon_right: item.meFlag },
										{ voice_icon_left: !item.meFlag },
										{ voice_icon_right_an: item.anmitionPlay && item.meFlag },
										{ voice_icon_left_an: item.anmitionPlay && !item.meFlag }
									]"></view>
								<view class="">{{JSON.parse(item.content).contentDuration}}''</view>
							</view>
							<!-- contentType = 2 图片 -->
							<view  	 v-if="item.contentType == 2" @tap="showPic(item)"	class="content contentType3">
								<u-image :width="parseImgSize(item,'w')" :height="parseImgSize(item,'h')"  :lazy-load="false"   mode="widthFix" :src="parseContent(item)">
									<u-loading slot="loading"></u-loading>
								</u-image>
							</view>
						</view>
					</view> 
			</scroll-view>
		</view>
	
		<view class="content">
			<!-- 底部聊天输入框 -->
			<view  class="input-box">
				<view class="input-box-flex">
					<image v-if="chatType === 'voice'" class="icon_img" :src="require('@/static/voice.png')"
						@click="switchChatType('keyboard')"></image>
					<image v-if="chatType === 'keyboard'" class="icon_img" :src="require('@/static/keyboard.png')"
						@click="switchChatType('voice')"></image>
					<view class="input-box-flex-grow">
						<view class="textArea-box"  v-if="chatType === 'voice'">
							<scroll-view scroll-y="true" class="inputScroll" show-scrollbar>
								<textarea 
									:disabled="connError"
									style="text-indent:5upx;" auto-height="true" 
									placeholder-style="color:#DDDDDD;"
									 :cursor-spacing="10"
									 :confirm-hold="true"
									 :focus="inputFocusFlag"
									v-model="sendStr" :cursor="sendStr.length" :maxlength="-1" />
							</scroll-view>
						</view>	
							
						<view class="voice_title" v-if="chatType === 'keyboard'"
								@touchstart.stop.prevent="startVoice"
								@touchmove.stop.prevent="moveVoice"
								@touchend.stop="endVoice"
								@touchcancel.stop="cancelVoice"
								:style="{ background: recording ? '#c7c6c6' : '#FFFFFF' }">
							{{ voiceTitle }}
						</view>
					</view>

					<image class="icon_btn_add" :src="require('@/static/emoji.png')" @click="changeEmojiBox"></image>
					<!-- 功能性按钮 -->
					<image class="icon_btn_add" :src="require('@/static/add.png')"   @click="changeDrawer"></image>
					
					<view  @touchend.prevent="sendText"  class="send" :class="chatType === 'voice'?'hidden':''">
						<view class="btn">发送</view>
					</view>

				</view>

				<view class="fun-box u-border-top" :class="{'show-fun-box':showFunBtn}">
					<u-grid :col="4" hover-class="contentType2-hover-class" :border="false" @click="clickGrid">
						<u-grid-item v-for="(item, index) in funList" :index="index" :key="index" bg-color="#f8f8f8" :custom-style="{padding:'20rpx 0'}">
							<view class="u-flex u-row-center u-col-center" style="background-color: #FFFFFF;width: 64rpx;height: 64rpx;border-radius: 10rpx;">
								<u-icon :name="item.icon" :size="52"></u-icon></view>
							<view class="grid-text">{{ item.title }}</view>
						</u-grid-item>
					</u-grid>
				</view>
				
				<view class="fun-box u-border-top" :class="{'show-fun-box':showEmojiBox}">
					<!-- 表情 :class="{hidden:hideEmoji}"-->
						<swiper class="emoji-swiper"  indicator-dots="true" duration="150">
							<swiper-item v-for="(page,pid) in faceList" :key="pid">
								<view v-for="(em,eid) in page" :key="eid" @tap="addEmoji(em)">
									<image mode="widthFix" :src="'/static/emoji/'+em.url"></image>
								</view>
							</swiper-item>
						</swiper>
				</view>

			</view>
			
		<!-- //语音动画 -->
			<view class="voice_an"  v-if="recording">
				<view class="voice_an_icon">
					<view id="one" class="wave"></view>
					<view id="two" class="wave"></view>
					<view id="three" class="wave"></view>
					<view id="four" class="wave"></view>
					<view id="five" class="wave"></view>
					<view id="six" class="wave"></view>
					<view id="seven" class="wave"></view>
				</view>
				<view class="text">{{voiceIconText}}</view>
			</view>
		</view>

		<chunLei-popups v-model="toolTipFlag" :popData="toolTipData" @tapPopup="tapPopup"
						:x="toolTipX" :y="toolTipY"  direction="row" theme="dark" :dynamic="true">
		</chunLei-popups>	
		
		
		<u-popup v-model="delPopUpObj.isShow" ref="delPopup" border-radius="10rpx" mode="bottom" :mask="true">
			<view class="uni-tip-delMsg">
				<view class="uni-tip-content u-border-bottom">确认撤回该条信息?</view>
				<view class="u-flex-col u-row-around u-col-center u-margin-top-20">
					<view class="uni-tip-button" style="color: red;" @click="delPopConfirm()">确定</view>
					<view
						style="width: 100%; height: 10rpx;line-height: 10rpx;background-color: #dcdfe6;margin: 20rpx 0rpx;">
						<u-line color="#dcdfe6" margin="1rpx" />
					</view>
					<view class="uni-tip-button" @click="delPopCancel()">取消</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import config from '@/common/environment.js';
	import permission from '@/util/mobilePermission/permission.js';
	const WEBSOCKET_SERVICE = config.WEBSOCKET_SERVICE;
	import {faceUtils} from '@/util/util.js';
	import chunLeiPopups from "@/components/chunLei-popups/chunLei-popups.vue";
	export default {
		components:{
			chunLeiPopups
		},
		data() {
			return {
				socketTask:null,
				//当前群聊
				currentChatGroup: {
					id: '',
					chatGroupName: '群聊',
				},
				wsOnlion: false, //websocket是否在线,
				pageNum:1,
				pageSize:15,
				messageList: [],
			    scrollIntoView:'',
				loadingmMore:false,
				scrollTop:100,
				scrollAnimation:true,
				loadingMsg: true, //标识是否正在获取数据
				chatType: 'voice', // 图标类型 'voice'语音 'keyboard'键盘
				sendStr: '', //发送的文字信息
				Recorder: uni.getRecorderManager(),
				Audio: uni.createInnerAudioContext(),
				recording: false, //标识是否正在录音
				isStopVoice: false, //加锁 防止点击过快引起的当录音正在准备(还没有开始录音)的时候,却调用了stop方法但并不能阻止录音的问题
				voiceInterval:null,
				voiceTime:0, //总共录音时长
				canSend:true, //是否可以发送	
				PointY:0, //坐标位置
				voiceIconText:"正在录音...",		
				voiceTitle: '按住 说话',
				AudioExam:null, //正在播放音频的实例	
				showFunBtn: false, //是否展示功能型按钮
				showEmojiBox:false, //是否显示表情弹窗
				funList: [{
						icon: "photo-fill",
						title: "照片",
						uploadType: ["album"]
					},
					{
						icon: "camera-fill",
						title: "拍摄",
						uploadType: ["camera"]
					},
					{
						icon: "/static/image/chat/dir.png",
						title: "文件",
						uploadType: ["camera"]
					},
					{
						icon: "red-packet-fill",
						title: "红包",
					},
					{
						icon: "/static/image/chat/call.png",
						title: "语音通话",
					},
					{
						icon: "/static/image/chat/video.png",
						title: "视频通话",
					},
					{
						icon: "map-fill",
						title: "位置",
					},
				],
				inputFocusFlag: false,
				scrollViewHeight: 600,
				faceList: faceUtils.emojiList(),
				faceMap: faceUtils.faces(),
				connError:false,
				advShow:true,
				toolTipFlag:false,
				toolTipData:[
					{id:1, icon:'/static/image/chat/copy.png', title:'复制',disabled:false},
					{id:2, icon:'/static/image/chat/zhuanfa.png',title:'转发'},
					{id:3,icon:'/static/image/chat/revert.png', title:'撤回'},
				],
				toolTipX:0,
				toolTipY:0,
				currentHandleMsg:{},
				delPopUpObj: {
					isShow: false,
					param: '',
				},
			};
		},
		created: function() {
			let scrollViewHeight = this.$u.sys().windowHeight - 160;
			this.scrollViewHeight = scrollViewHeight;
		},
		//监听信息滚动	
		onReady() {
			let that=this;
			uni.onKeyboardHeightChange(res => {
				//如果键盘弹起
				if (res.height != 0) {
					this.showFunBtn = false;
					this.showEmojiBox = false;
					this.scrollViewHeight = this.$u.sys().windowHeight - res.height - 135;
				} 
				//键盘收起
				else {
					this.scrollViewHeight = this.$u.sys().windowHeight - 160;
				}
				//这个保证信息在底部,显示最后一条信息
				this.scrollTop=that.scrollViewHeight+9000;
				console.log("===onReady===",this.scrollTop);
			});
			
		},
		//页面加载获取群聊信息
		onLoad(option) {
			//console.log("聊天界面初始化参数", option);
			this.currentChatGroup.id = option.chatGroupId;
			//查询群聊信息
			//this.getChatGroupInfo();
			
			//录音开始事件
			this.Recorder.onStart(e => {
				
				this.beginVoice();
			});
			//录音结束事件
			this.Recorder.onStop(res => {
				clearInterval(this.voiceInterval);
				this.handleRecorder(res);
			});
	
			//音频停止事件
			this.Audio.onStop(e => {
				this.closeAnmition();
			});
	
			//音频播放结束事件
			this.Audio.onEnded(e => {
				this.closeAnmition();
			});
		},
		//页面显示初始化
		onShow: function() {
			let that = this;
			that.scrollAnimation =false;
			this.getChatGroupInfo();
			this.initWebScoket();
		},
		onHide: function() {
			let  that = this;
			that.Audio.stop();
			that.closeWebScoket();
		},
		onUnload() {
			let that = this;
			that.Audio.stop();
			that.closeWebScoket();
		},
		//监听返回
		onBackPress(options) {  
			this.customBack();  
			return true;  
		},
		
		methods: {
			//自定义返回
			customBack: function() {
				this.Audio.stop();
				//退出聊天界面的时候也需要重置用户的未读信息为已读,因为存储的时候非发送者都是存的未读状态
				let chatGroupId=this.currentChatGroup.id;
				let currentUserId=this.vuex_userInfo.id;
				let paramData={"chatGroupId":chatGroupId,"userId":currentUserId};
				this.$u.api.chatGroup.clearUnReadNum(paramData).then(res => {
					this.$u.route({
						url: "pages/chat/chatGroupList",
						type: 'switchTab'
					})
				})
			},
			//跳转群组详情
			toGroupDetail: function() {
				let that = this;
				if(that.connError){
					that.globalUtil.utilAlert("您已被踢出群聊");
					return;
				}
			    let param = {
					chatGroupId: that.currentChatGroup.id,
					chatGroupType:that.currentChatGroup.chatGroupType,
			    };
				that.$u.route({
					url:'pages/chat/chatGroup/chatDetail',
					params:param
				});
				return;
			},
			//获取群组信息
			getChatGroupInfo: function() {
				let that = this;
				let param = {
					chatGroupId: that.currentChatGroup.id
				};
				that.$u.api.chatGroup.getChatGroupInfo(param).then(res => {
					if (res.code == 200) {
						let data = res.data;
						that.currentChatGroup = data.imGroup;
						//console.log("群信息",that.currentChatGroup);
						that.getHistoryMessage();
					} else {
						that.globalUtil.utilAlert("群信息获取失败");
						return;
					}
				})
			},
			//主动关闭websocket
			closeWebScoket: function() {
				let that = this;
				that.wsOnlion = false;
				that.socketTask.close({
				  success(res) {
				    that.wsOnlion = false;
				    console.log("列表界面websocket关闭成功", res)
				  },
				  fail(err) {
				    console.log("列表界面websocket关闭失败", err)
				  }
				})
			},
			//初始话websocket服务
			initWebScoket: function() {
				let that = this;
				let userId = that.vuex_userInfo.id;
				let chatGroupId = that.currentChatGroup.id;
				let url = WEBSOCKET_SERVICE + userId + "/" + chatGroupId;
				console.log("webSocket链接地址:"+url);
				that.socketTask = uni.connectSocket({
					url: url,
					success(data) {
					    console.log("聊天长连接已建立完成");
					},
				});
				that.socketTask.onOpen(function(res) {
					console.log('WebSocket连接已打开！');
					that.wsOnlion = true;
					uni.hideLoading();
					that.socketTask.onMessage(function(res) {
						console.log("有新的信息");
						that.msgToScreen(res);
					});
				});
				that.socketTask.onError(function(res) {
					console.log('WebSocket异常，请检查！');
					that.closeWebScoket();
					//异常断开,重连服务;
				});
				that.socketTask.onClose(function(res) {
					console.log('WebSocket 已关闭！');
					that.wsOnlion = false;
				});
			},
			//获取历史消息,带分页
			getHistoryMessage:function(){
				let that = this;
				that.messageList=[];
				that.globalUtil.utilLoading("页面加载中...");
				let param = {
					chatGroupId: that.currentChatGroup.id,
					pageNum:1,
					pageSize:that.pageSize,
				};
				that.$u.api.chatGroup.getChatGroupHistoryMessage(param).then(res => {
					if (res.code == 200) {
						let data = res.data;
						if(data.length>0){
							for (var i = 0; i < data.length; i++) {
								let contentType= data[i].contentType;
								if(contentType==4){
									 data[i].anmitionPlay=false;
								}
							}
							//console.log("信息列表",data);
							that.messageList=data.reverse();
						}
					    //渲染完成以后让滚动到底部
						setTimeout(function(){
							that.scrollTop=9999;
							that.scrollAnimation = true;
							uni.hideLoading();
						},1500);
					} else {
						that.globalUtil.utilAlert("群信息获取失败");
						uni.hideLoading();
						return;
					}
				})
			},
			//向上滑动加载更多历史信息数据
			loadMoreHistoryMsg:function(){
				let that=this;
				if(that.loadingmMore){
					that.loadingmMore=false;
					return;
				}
				that.pageNum++;
				let param = {
					chatGroupId: that.currentChatGroup.id,
					pageNum:that.pageNum,
					pageSize:that.pageSize,
				};
				console.log("上划加载更多历史数据分页参数",param);
				let oldScrollViewId=that.messageList[0].id;
				that.scrollAnimation = false; //关闭滑动动画
				that.loadingmMore=true;
				that.$u.api.chatGroup.getChatGroupHistoryMessage(param).then(res => {
					//console.log("分页数据",res);
					if (res.code == 200) {
						let data = res.data;
						if(data!=null&&data.length>0){
							for (var i = 0; i < data.length; i++) {
								let contentType= data[i].contentType;
								if(contentType==4){
									 data[i].anmitionPlay=false;
								}
							}
							let moreData= data.reverse();
							that.messageList=moreData.concat(that.messageList);
							that.$nextTick(function(){
								/* let screenHeight= that.$u.sys().windowHeight;
								let scrollTop= Math.ceil(screenHeight/2)+500;
								that.scrollTop=scrollTop; */
								console.log("scrollIntoView",that.scrollIntoView);
								that.scrollIntoView="msg_"+oldScrollViewId;
								setTimeout(function(){
									that.loadingmMore=false;
									that.scrollAnimation=true;
								},2000)
							})
						}
						else{
							that.pageNum--;
							that.loadingmMore=false;
							//that.globalUtil.utilAlert("暂无更多信息记录");
							return;
						}
					} else {
						that.pageNum--;
						that.loadingmMore=false;
						//that.globalUtil.utilAlert("暂无更多信息记录");
						return;
					}
				})
			},
			//操作项	
			showToolTip:function(e,index){
				this.toolTipX= e.touches[0].clientX;
				this.toolTipY = e.touches[0].clientY;
				this.toolTipFlag=!this.toolTipFlag;
				this.currentHandleMsg=this.messageList[index];
				console.log("this.currentHandleMsg",this.currentHandleMsg);
				this.currentHandleMsg.msgIndex=index;
				let contentType= this.currentHandleMsg.contentType;
				if(this.currentHandleMsg.meFlag==false){
					this.toolTipData=[
						{id:1, icon:'/static/image/chat/copy.png', title:'复制',disabled:(contentType!=1)},
						{id:2, icon:'/static/image/chat/zhuanfa.png',title:'转发',disabled:false},
						{id:3,icon:'/static/image/chat/revert.png', title:'撤回',disabled:true},
					]
					return;
				}else{
					let sendTimeMills= this.globalUtil.parseTime(this.currentHandleMsg.createTime).getTime();
					let nowTimeMills=new Date().getTime();
					let diff = nowTimeMills - sendTimeMills;
					console.log("diff", diff);
					let twoMinutes = 60 * 1000 * 2;
					if(diff>twoMinutes){
						console.log("不能撤回");
						this.toolTipData=[
							{id:1, icon:'/static/image/chat/copy.png', title:'复制',disabled:(contentType!=1)},
							{id:2, icon:'/static/image/chat/zhuanfa.png',title:'转发',disabled:false},
							{id:3,icon:'/static/image/chat/revert.png', title:'撤回',disabled:true},
						]
						return;
					}else{
						this.toolTipData=[
							{id:1, icon:'/static/image/chat/copy.png', title:'复制',disabled:(contentType!=1)},
							{id:2, icon:'/static/image/chat/zhuanfa.png',title:'转发',disabled:false},
							{id:3,icon:'/static/image/chat/revert.png', title:'撤回',disabled:false},
						]
						return;
					}
				}
			},
			tapPopup(e){
				let that=this;
				console.log(" that.currentHandleMsg", that.currentHandleMsg);
				//console.log("操作选项",e);
				if(e.title=="撤回"){
					that.revertMsg();
				}
				if(e.title=="复制"){
					let content=that.currentHandleMsg.content;
					if(content.length>0){
						let copyContent=JSON.parse(content).text;
						that.globalUtil.uniCopy({
						  content:copyContent,
						  success:(res)=>{
						    uni.showToast({
						      title: res,
						      icon: 'none'
						    })
						  },
						  error:(e)=>{
						    uni.showToast({
						      title: e,
						      icon: 'none',
						      duration:3000,
						    })
						  }
						})
					}
					that.toolTipFlag=false;
					return;
				}
				if(e.title=="转发"){
					that.globalUtil.utilAlert("功能尚未开放!");
					that.toolTipFlag=false;
					return
				}
			},
			
			//判断是否可以撤回信息,根据时间推算
			revertMsg() {
				let that = this;
				that.toolTipFlag=false;
				that.delPopUpObj.isShow = true;
				that.$refs.delPopup.open();
			},
			
			delPopConfirm: function() {
				let that = this;
				console.log("打开删除消息弹框",that.currentHandleMsg);
				that.$u.api.chatGroup.revertMessageById(that.currentHandleMsg).then(res => {
					console.log("撤回消息成功",res);
					if (res.code == 200) {
						console.log("撤回消息成功",delIndex);
					} else {
						that.globalUtil.utilAlert("撤回信息失败!");
						uni.hideLoading();
						return;
					}
				});
				setTimeout(function() {
					that.delPopCancel();
				}, 500)
		
			},
			
			delPopCancel: function() {
				let that = this;
				that.delPopUpObj.isShow = false;
				that.$refs.delPopup.close();
				that.currentHandleMsg={};
				that.toolTipFlag=false;
			},
			
/*----------------------------------------------------录音相关 start-------------------------------------- */		
			//准备开始录音
			startVoice(e) {
				if(!this.Audio.paused){
					//如果音频正在播放 先暂停。
					this.stopAudio(this.AudioExam)
				}
				this.recording = true;
				this.isStopVoice = false;
				this.canSend = true;
				this.voiceIconText = "正在录音..."
				this.PointY = e.touches[0].clientY;
				this.Recorder.start({
					format: 'mp3'
				});
			},
			//录音已经开始
			beginVoice(){
				let that=this;
				if (that.isStopVoice) {
					that.Recorder.stop();
					return;
				}
				that.voiceTitle = '松开 结束'
				that.voiceInterval =  setInterval(()=>{
					console.log("that.voiceTime",that.voiceTime);
					if (that.voiceTime>49) {
						that.voiceIconText = "录音结束倒计时[" + (60 - that.voiceTime) + "]s";
					};
					if(that.voiceTime==60){
						clearInterval(that.voiceInterval);
						that.endVoice();
					}
					that.voiceTime ++;
				},1000)
			},
			//move 正在录音中
			moveVoice(e){
				const PointY = e.touches[0].clientY;
				const slideY = this.PointY - PointY;
				if(slideY > uni.upx2px(120)){
					this.canSend = false;
					this.voiceIconText = '松开手指 取消发送 '
				}else if(slideY > uni.upx2px(60)){
					this.canSend = true;
					this.voiceIconText = '手指上滑 取消发送 '
				}else{
					this.voiceIconText = '正在录音... '
				}
			},
			//结束录音
			endVoice() {
				this.isStopVoice = true; //加锁 确保已经结束录音并不会录制
				this.Recorder.stop();
				this.voiceTitle = '按住 说话'
			},
			//录音被打断
			cancelVoice(e){
				console.log("路由被打断",e);
				this.voiceTime = 0;
				this.voiceTitle = '按住 说话';
				this.canSend = false;
				this.Recorder.stop();
			},
			//处理录音文件
			handleRecorder({ tempFilePath,duration }) {
				if(this.voiceTime<1){
					this.voiceIconText="说话时间过短";
					setTimeout(()=>{
						this.recording = false;
					},500)
					return;
				}
				let contentDuration = this.voiceTime;
				this.voiceTime = 0;
				this.recording = false;
				clearInterval(this.voiceInterval);
				let uploadFileUrl = this.$u.api.multipartAddress.updload+"/chattingFiles";
				let voiceFile={
					type:4,	 //信息内容类型   1-文本 2-图片 3-视频  4-语音信息 5-文件 6-其他
					filePath:tempFilePath,
					uploadUrl:uploadFileUrl,
					contentDuration: Math.ceil(contentDuration)
				}
				console.log("语音文件",voiceFile);
				if(this.canSend){
					this.uploadFile(voiceFile);
					return;
				}
			    else{
					console.log("=====已经取消发送语音信息====")
					return;
				}
			},
			//控制播放还是暂停音频文件
			handleAudio(item) {
				this.AudioExam = item;
				this.Audio.paused ? this.playAudio(item) : this.stopAudio(item);
			},
			//播放音频
			playAudio(item) {
				this.Audio.src = JSON.parse(item.content).url;
				this.Audio.hasBeenSentId = item.id;
				this.Audio.play();
				item.anmitionPlay = true;
			},
			//停止音频
			stopAudio(item) {
				item.anmitionPlay = false;
				this.Audio.src = '';
				this.Audio.stop();
			},
			//关闭动画
			closeAnmition() {
				const hasBeenSentId = this.Audio.hasBeenSentId;
				const item = this.messageList.find(it => it.id == hasBeenSentId);
				item.anmitionPlay = false;
			},
/*-------------------------------------录音相关方法块  end---------------------------------------------------*/			
			//添加表情
			addEmoji(em) {
				this.sendStr += em.alt;
			},
			//发送文本信息
			sendText: function() {
				let that = this;
				if(that.sendStr.length<1){
					uni.hideKeyboard();
					that.globalUtil.utilAlert("不能发送空字符串");
					return;
				}
				//如果文字中有表情,需要转换处理
				let formatStr = this.replaceEmoji(this.sendStr);
				let content= {
						"text": formatStr,					//文本内容
				}
				that.sendMsg(1,1,content);
			},
			replaceEmoji(str) {
				let replacedStr = str.replace(/\[([^(\]|\[)]*)\]/g, (item, index) => {
					for (let i = 0; i < this.faceList.length; i++) {
						let row = this.faceList[i];
						for (let j = 0; j < row.length; j++) {
							let EM = row[j];
							if (EM.alt == item) {
								//在线表情路径，图文混排必须使用网络路径，请上传一份表情到你的服务器后再替换此路径
								//比如你上传服务器后，你的100.gif路径为https://www.xxx.com/emoji/100.gif 则替换onlinePath填写为https://www.xxx.com/emoji/
								// let onlinePath = 'https://s2.ax1x.com/2019/04/12/'
								// let imgstr = '<img alt="'+EM.alt+'" src="'+onlinePath+this.onlineEmoji[EM.url]+'">';
								let imgstr = "face" + EM.alt;
								console.log("imgstr: " + imgstr);
								return imgstr;
							}
						}
					}
				});
				console.log("replacedStr",replacedStr);
				return replacedStr;
			},
			
			//发送消息
			sendMsg: function(msgType,contentType,contentObj) {
				let that=this;
				let msg={
					messageType: msgType==null?1:msgType,  		//信息类型0:系统信息   1表示用户信息
					fromUserId: that.vuex_userInfo.id,   		//发送信息的人
					chatGroupId: that.currentChatGroup.id,		//聊天群聊id
					platFrom:1,									//手机端
					contentType:contentType,					//信息内容类型   1-文本 2-图片 3-视频  4-语音信息 5-文件 6-其他
					content:JSON.stringify(contentObj), 
				}
				if (that.wsOnlion == true) {
					that.socketTask.send({
						data: JSON.stringify(msg),
						success() {
							console.log("webscoket发送信息成功");
						},
						fail() {
							that.globalUtil.utilAlert("网络不佳,发送失败");
						}
					});
				} else {
					console.log("websocket已经掉线");
					if(that.connError==true){
						that.globalUtil.utilAlert("您已被退出群聊!");
						return;
					}
					that.globalUtil.utilAlert("信息发送失败");
					return;
				}
			},
			//接收到信息,渲染到信息面板上去,
			// 不能滚动到底部
			msgToScreen:function(res){
				let that=this;
				if(res!=null&&res.data!=null&&res.data.length>0){
					let msgFromServer= JSON.parse(res.data);
					console.log("msgFromServer",msgFromServer);
					//群聊被解散
					if(msgFromServer.messageType==-1){
						that.closeWebScoket();
						that.globalUtil.utilAlert("群聊已经被解散");
						that.$u.route({
							url: "pages/chat/chatGroupList",
							type: 'switchTab'
						})
						return;
					}
					if(msgFromServer.contentType==4){
						msgFromServer.anmitionPlay=false;
					}
					msgFromServer.msgType=msgFromServer.messageType;
					if(msgFromServer.meFlag==true){
						that.sendStr="";
					}
					let msgType= msgFromServer.msgType;
					let content= msgFromServer.content;
					if(msgType==2){
						let contentObj= JSON.parse(content);
						let currentUserId=that.vuex_userInfo.id;
						console.log("系统消息",contentObj);
					    if(contentObj.contentType==2&&contentObj.delMember==currentUserId){
							contentObj.text="您已经被剔除群聊!";
							msgFromServer.content=JSON.stringify(contentObj);
							that.messageList.push(msgFromServer);
							that.closeWebScoket();
							that.connError=true;
						}
						if(contentObj.optionType==-2){
							let revertMsg= contentObj.delMsg;
							let delIndex=-1;
							console.log("有人撤回了一条信息",contentObj);
							for (var i = 0; i < that.messageList.length; i++) {
							  let messageItem=that.messageList[i];
							   if(revertMsg.id==messageItem.id){
								    delIndex=i;
							   } 
							}
							if(delIndex!=-1){
								that.messageList.splice(delIndex,1);
							}
							let userName=msgFromServer.meFlag?"我":contentObj.optionUserName;
							msgFromServer.userName=userName;
							msgFromServer.content=JSON.stringify(contentObj);
							that.messageList.push(msgFromServer);
						} 
					}else{
						that.messageList.push(msgFromServer);
					}
					that.$nextTick(function(){
						setTimeout(function(){
							that.scrollIntoView="msg_"+msgFromServer.id;
							that.scrollTop=that.scrollTop+500;
						},200)
					})
					let fromUserId= msgFromServer.fromUserId;
					let chatGroupId=msgFromServer.chatGroupId;
					if(fromUserId!= that.vuex_userInfo.id){
						that.globalUtil.palyMsgTipSelected(that,chatGroupId);
					}
					if(msgFromServer.msgType==2){
						let that = this;
						let param = {
							chatGroupId: that.currentChatGroup.id
						};
						that.$u.api.chatGroup.getChatGroupInfo(param).then(res => {
							if (res.code == 200) {
								let data = res.data;
								that.currentChatGroup = data.imGroup;
							} else {
								that.globalUtil.utilAlert("获取最新群信息失败");
								return;
							}
						})
					}
				}
			},
			parseContent:function(item){
				let msgType= item.msgType;
				let contentType=item.contentType;
				if(contentType==1){
					let content= JSON.parse(item.content);
					let msgStr=content.text;
					let sysType= content.contentType;
					let optionType= content.optionType;
					if(sysType!=null&&sysType!=undefined&&sysType==1){
						if(msgStr.length>0){
							return "群主发布了新的公告";
						}
						else{
							return "群主作废了群公告";
						}
					}
					if(optionType==-2){
					//	console.log("item",item);
						return item.userName+":撤回了一条消息";
					}
					let transText= this.globalUtil.transform(msgStr, "", "");
					return transText;
				}else{
					return JSON.parse(item.content).url;
				}
			},
			showNotice:function(){
				let that=this;
				console.log("查看群公告");	
			},
			
			parseShowTime:function(item){
				if(item.createTime==null){
					return false;
				}
				let crteateTimeStr= item.createTime.replace(/-/g, "/");//时间转换
				let createTime=new Date(crteateTimeStr).getTime();
				let nowTime=new Date().getTime();
				let during= nowTime-createTime;
				if(during>1000*60*3){
					return true;
				}else{
					return false;
				}
				//Date.now()-new Date(create_time)>3*60*60*1000
				
			},
			
			//内容转换(暂时不用)
			transformContent:function(message){
				let contentStr=message.content;
				let contentObj=JSON.parse(contentStr);
				let text =contentObj.text;
				let fileSuffix =contentObj.fileSuffix;
				let fileSize =contentObj.fileSize;
				//信息内容转换
				let transText= this.globalUtil.transform(text, fileSize, fileSuffix);
				contentObj.text=transText;
				message.content=JSON.stringify(contentObj);
			},
			
		    parseImgSize:function(item,type){
				if(type=="h"){
					let height=JSON.parse(item.content).height;
					if(height==null||height==undefined){
						return "auto";
					}else{
						return height*2;
					}
				}
				else{
				 	let width=JSON.parse(item.content).width;
				 	if(width==null||width==undefined){
				 		return 300;
				 	}else{
				 		return width*2;
				 	}
				}
			},
			//切换语音或者键盘方式
			switchChatType(type) {
				let that=this;
				if(that.connError){
					that.globalUtil.utilAlert("您已被踢出群聊");
					return;
				}
				this.chatType = type;
				//底部菜单隐藏
				this.showFunBtn = false;
				//表情弹窗
				if(this.showEmojiBox==true){
					this.showEmojiBox = false;
					setTimeout(function(){
						that.scrollViewHeight = that.$u.sys().windowHeight - 160;
						that.scrollTop=that.scrollViewHeight+1000;
					},300)
				}
				if (type == "voice") {
					this.inputFocusFlag = true;
				}else{
					if (uni.getSystemInfoSync().platform == "android") {
						permission.requestAndroid("android.permission.RECORD_AUDIO"); //Android请求录音权限
					} else {
						permission.requestIOS("record"); //ios请求录音权限
					}
				}
			},
			//切换功能性按钮
			changeDrawer() {
				let that=this;
				that.showEmojiBox=false;
				that.showFunBtn = !that.showFunBtn;
				uni.hideKeyboard();
				if (that.showFunBtn) {
					setTimeout(function(){
						that.scrollViewHeight = that.$u.sys().windowHeight - 320;
						that.scrollTop=that.scrollViewHeight+1000;
					},300)
					
				}else {
					setTimeout(function(){
						that.scrollViewHeight = that.$u.sys().windowHeight - 160;
						that.scrollTop=that.scrollViewHeight+1000;
					},300)
				}
			
			},
			//表情弹窗
			changeEmojiBox:function(){
				let that=this;
				that.showFunBtn=false;
				that.showEmojiBox = !that.showEmojiBox;
				uni.hideKeyboard();
				if (that.showEmojiBox) {
					this.chatType = "voice";
					setTimeout(function(){
						that.scrollViewHeight = that.$u.sys().windowHeight - 320;
						that.scrollTop=that.scrollViewHeight+1000;
					},300)
				}else {
					setTimeout(function(){
						that.scrollViewHeight = that.$u.sys().windowHeight - 160;
						that.scrollTop=that.scrollViewHeight+1000;
					},300)
				} 
			},
			scrollViewScrolling:function(){
				this.toolTipFlag=false;
			},
			//触摸页面
			hideDrawer() {
				this.toolTipFlag=false;
				if (this.showFunBtn == true) {
					uni.hideKeyboard();
					this.showFunBtn = false;
					this.scrollViewHeight = this.$u.sys().windowHeight - 150;
					this.scrollTop=this.scrollViewHeight+1000;
				}
				if (this.showEmojiBox == true) {
					uni.hideKeyboard();
					this.showEmojiBox = false;
					this.scrollViewHeight = this.$u.sys().windowHeight - 150;
					this.scrollTop=this.scrollViewHeight+1000;
				}
			},
			//点击宫格时触发
			clickGrid(index) {
				if (index == 0) {
					this.chooseImage('album')
				} else if (index == 1) {
					this.chooseImage('camera')
				}else{
					this.globalUtil.utilAlert("功能尚未开放!");
					return;
				}
			},
			
			//选照片 or 拍照
			chooseImage(type) {
				let that = this;
				uni.chooseImage({
					count: 9,
					sourceType: [type],
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					success: (res) => {
						for (let i = 0; i < res.tempFilePaths.length; i++) {
							uni.getImageInfo({
								src: res.tempFilePaths[i],
								success: (image) => {
									image.type =2;    ///信息内容类型   1-文本 2-图片 3-视频  4-语音信息 5-文件 6-其他
									image.filePath = image.path;
									let uploadFileUrl = this.$u.api.multipartAddress.updload;
									image.uploadUrl=uploadFileUrl+"/chattingFiles";
									let maxW = uni.upx2px(350); //350是定义消息图片最大宽度
									let maxH = uni.upx2px(350); //350是定义消息图片最大高度
									if (image.width > maxW || image.height > maxH) {
										let scale = image.width / image.height;
										image.width = scale > 1 ? maxW : maxH * scale;
										image.height = scale > 1 ? maxW / scale : maxH;
									}
									that.uploadFile(image);
								}
							});
						}
					},
					fail() {
						console.log("选择图片上传发送异常");
					}
				});
			},
			//上传文件到服务器
			uploadFile(obj) {
				let that=this;
				console.log("上传文件的参数", obj);
				if(that.connError){
					that.globalUtil.utilAlert("您已被踢出群聊");
					return;
				}
				let uploadUrl = obj.uploadUrl;
				let filePath = obj.filePath;
				let isSuccess = false;
				let sizeError = 0;
				if (uploadUrl && filePath) {
					let msg = {};
					const uploadTask = uni.uploadFile({
						url: uploadUrl,
						filePath: filePath,
						name: 'fileName',
						header: {
							'Access-Control-Allow-Origin': '*',
							'TOKEN_OA': that.vuex_token,
						},
						success: (uploadFileRes) => {
							if (uploadFileRes.statusCode == 200 && uploadFileRes.data.length > 0) {
								let resObj = JSON.parse(uploadFileRes.data);
								console.log("文件上传响应回调数据", resObj);
								if (resObj.code == 200) {
									let _url = that.$u.api.multipartAddress.getFileByPath + resObj.data;
									 msg.url = _url;
									 let suffix = resObj.data.substring(resObj.data.lastIndexOf('.') + 1, resObj.data.length);
									 msg.fileSuffix = suffix;
									 msg.fileName = resObj.data;
									 if (obj.type ==2) {
										msg.width=obj.width;
										msg.height=obj.height;
									 }
									 if (obj.type ==4) {
										msg.contentDuration=obj.contentDuration;
									 }
									 isSuccess = true;
									 uni.hideLoading();
									 that.sendMsg(1, obj.type,msg);
								} else {
									that.globalUtil.utilAlert("发送失败!");
									return;
								}
							} else {
								that.globalUtil.utilAlert("发送异常!");
								return;
							}
						},
						fail: function() {
							if (isSuccess == false && sizeError == 1) {
								uni.showModal({
									title: '提示:',
									confirmText: '我知道了',
									cancelText: '重新上传',
									confirmColor: '#007AFF',
									cancelColor: '#48CC94',
									content: "【失败! 文件上传不允许超出300M...】",
									success: function(res) {
										if (res.confirm) {
											console.log('用户点击确认按钮');
										} else if (res.cancel) {
											console.log("取消上传");
										}
									}
								});
							} else {
								that.globalUtil.utilAlert("文件上传异常");
							}
							uni.hideLoading();
							return;
						}
					});
					uploadTask.onProgressUpdate((res) => {
						if (res.totalBytesExpectedToSend > 314572800) {
							sizeError = 1;
							uploadTask.abort();
							return;
						} else {
							msg.fileSize = this.globalUtil.byteConvert(res.totalBytesExpectedToSend);
						}
					});
				} else {
					this.globalUtil.utilAlert("上传文件的参数丢失");
					console.log("上传文件的参数丢失");
					return;
				}
			},
			
			showPic(item){
				//console.log("item",item);
				let content=JSON.parse(item.content);
				let src= content.url;
				console.log("src",src);
				uni.previewImage({
					urls: [src],
				});
				return;
			}
			
		},
	};
</script>

<style lang="scss" scoped>
	@import './chatting.scss';

	.chatting-container {
		.custom-navbar {
			width: 100%;
			display: flex;
			flex: 1;
			flex-direction: row;
			justify-content: space-between;
			align-content: center;
			align-items: center;
			padding: 0 30rpx;

			.nav-left {}

			.nav-center {
				font-size: 36rpx;
				font-weight: bold;
			}

			.nav-right {}
		}

		.msg-container {
			width: 100%;
			.msg-box-scroller {
				//background-color: #f3f3f3;
				.message {
						padding: 13rpx 20rpx;
					}
					
					.message-item {
						display: flex;
						justify-content: flex-start;
						align-items: flex-start;
						align-content: flex-start;
						flex-wrap: nowrap;
						flex-direction: row;
				
						.img {
							width: 80rpx;
							height: 80rpx;
							border-radius: 5rpx;
						}
				
						.content {
							padding: 20rpx;
							max-width: 500rpx;
							border-radius: 10rpx;
							font-size: 28rpx;
							word-break: break-word;
							
							.richTextImg{
								//border: 1px solid red;
								.emoji{
									//border: 1px solid black;
									position: relative;
									top: 10rpx;
								}
							}
						}
						
						// 语音
						.contentType2 {
							display: flex;
							flex-direction: row;
							align-items: center;
							.voice_icon {
								height: 34rpx;
								width: 34rpx; 
								background-repeat: no-repeat;
								background-size: 100%;
							}
							.voice_icon_right {
								background-image: url(@/static/voice-left-3.png);
								margin-left: 10rpx;
							}
							.voice_icon_left {
								background-image: url(@/static/voice-right-3.png);
								margin-right: 10rpx;
							}
							.voice_icon_right_an {
								animation: voiceAn_right 1s linear alternate infinite;
							}
							.voice_icon_left_an {
								animation: voiceAn_left 1s linear alternate infinite;
							}
							@keyframes voiceAn_right {
								0% {
									background-image: url(@/static/voice-left-1.png);
								}
								50% {
									background-image: url(@/static/voice-left-2.png);
								}
								100% {
									background-image: url(@/static/voice-left-3.png);
								}
							}
							@keyframes voiceAn_left {
								0% {
									background-image: url(@/static/voice-right-1.png);
								}
								50% {
									background-image: url(@/static/voice-right-2.png);
								}
								100% {
									background-image: url(@/static/voice-right-3.png);
								}
							}
						}
						
						//图片
						.contentType3{
							padding: 0;
							border-radius: 2rpx;
							background-color: transparent !important;
							border: 1rpx solid #e4e7ed;
							.img{
								width: 200rpx;
								height: auto;
								max-width: 300rpx;
								max-height: 400rpx;
							}
						}
						.contentType3::after{
							border: none !important;
							display: none !important;
						}
						.content-type-right {
							flex-direction: row-reverse;
						}
				
						&.right {
							flex-direction: row-reverse;
				
							.content {
								background-color: $uni-color-success;
								margin-right: 28rpx;
								word-break: break-all;
								line-height: 36rpx;
								position: relative;
				
								&::after {
									content: '';
									display: block;
									width: 0;
									height: 0;
									border-top: 10rpx solid transparent;
									border-bottom: 10rpx solid transparent;
									border-left: 16rpx solid $uni-color-success;
									position: absolute;
									right: -16rpx;
									top: 30rpx;
								}
							}
						}
				
						&.left {
							.content {
								background-color: $u-bg-color;
								margin-left: 28rpx;
								word-break: break-all;
								line-height: 36rpx;
								position: relative;
				
								&::after {
									content: '';
									display: block;
									width: 0;
									height: 0;
									border-top: 10rpx solid transparent;
									border-bottom: 10rpx solid transparent;
									border-right: 16rpx solid $u-bg-color;
									position: absolute;
									left: -16rpx;
									top: 30rpx;
								}
							}
						}
					}
				
			}
		}
		
		.textArea-box{
			width: 100%;
			background-color: #FFFFFF;
			border-radius: 10upx;
			padding-left: 30upx;
			min-height: 70upx;
			display: flex;
			align-items: center;
			//margin-top: 10upx;
			textarea{
				width: 100%;
			}
		}
		
		.inputScroll {
			max-height: 180upx;
		}
		
		.send{
			//H5发送按钮左边距
			/* #ifdef H5
			margin-left: 20upx;
			/* #endif */
			flex-shrink: 0;
			width: 100upx;
			height: 100upx;
			display: flex;
			align-items: center;
			.btn{
				width: 90upx;
				height: 56upx;
				display: flex;
				justify-content: center;
				align-items: center;
				background:#19be6b;
				color: #fff;
				border-radius: 6upx;
				font-size: 24upx;
			}
		}
	}
	
	.uni-tip-delMsg {
		width: 100%;
		background: #FFFFFF;
		text-align: center;
		height: 300rpx;
		border-radius: 10px;
		//border: 1px solid red;
	}


	.uni-tip-title {
		text-align: center;
		font-weight: bold;
		font-size: 16px;
		color: #333;
	}

	.uni-tip-content {
		padding: 15px;
		font-size: 14px;
		color: #666;
	}

	.uni-tip-group-button {
		margin-top: 10px;
		display: flex;
	}

	.uni-tip-button {
		width: 100%;
		text-align: center;
		font-size: 14px;
		color: #3b4144;
		// margin-left: 20rpx;
	}
</style>
